import { type App } from 'vue';
import { pinia } from '@shared/internal/pinia';
import { clientUserDataStore, clientWorkflowSettings } from '@shared/internal/client';
import { useUserStoreWithOut } from '@/shared/store/user';
import { useWorkflowStoreWithOut } from '@main/store/workflow';
import type { UserSignProperties } from '#common/types/user';
import type { WorkflowSettingsProperties } from '#common/types/settings';
import { parseUrl } from '@shared/utils/url';
import type {
  productNotifyProperties,
  deepProductNotifyProperties,
  tasksProperties,
  deleteTaskProperties
} from '@main/socket/type';
import { emitter } from '@main/utils/mitt';

async function initialUserSignState() {
  const userStore = useUserStoreWithOut();

  const user = await clientUserDataStore.get('user');
  const tokenData = await clientUserDataStore.get('tokenData');
  if (user && tokenData) userStore.setUserDataAction({ user, tokenData } as UserSignProperties);
}

async function initialWorkflowState() {
  const workflowStore = useWorkflowStoreWithOut();

  const directory = (await clientWorkflowSettings.get(
    'directory'
  )) as Partial<WorkflowSettingsProperties>;
  if (directory)
    workflowStore.setDirectorySetting({
      draftDirectory: directory.draftDirectory,
      materialDirectory: directory.materialDirectory
    });

  //全局监听文件目录更新
  window.clientAppSdk.ipc.ipcRenderer.on('rc:workflow-settings-change', (_, args) => {
    workflowStore.setDirectorySetting(args[0] as Partial<WorkflowSettingsProperties>, true);
  });

  //全局接收协议参数
  window.clientAppSdk.ipc.ipcRenderer.on('rc:enter-protocol-data', (_, url: string) => {
    const { host, query } = parseUrl(url);
    console.log('rc:enter-protocol-data', url, { host, query });
    if (host == 'workflow' && query.title) workflowStore.addContentAction(query.title);
  });

  //全局接收商品处理通知
  emitter.on(
    'product-handle-reply',
    (data: { product_id: number } & (productNotifyProperties | deepProductNotifyProperties)) => {
      const content = workflowStore.getContentByProductId(data.product_id);
      if (!content.value) return;
      workflowStore.setContentAction(
        {
          ...content.value,
          ...data,
          stepwise: [...content.value.stepwise!, 'product_name' in data ? 2 : 3]
        },
        'product_id'
      );
    }
  );

  //全局接收新增任务通知
  emitter.on('receive-task', (data: tasksProperties) => {
    data.tasks.forEach((task) => {
      workflowStore.addContentAction(task);
    });
  });

  //全局接收删除任务通知
  emitter.on('delete-task', (data: deleteTaskProperties) => {
    workflowStore.deleteContentByTaskIdsAction(data.taskProductIds);
  });
}

export async function setupStore(app: App) {
  app.use(pinia);
  await initialUserSignState();
  await initialWorkflowState();
}
